/* 
 * $Id$
 * 
 * Copyright (c) 2007-13 Stephane GALLAND.
 * 
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 * 
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 * This program is free software; you can redistribute it and/or modify
 */
package fr.utbm.gi.vi51.project.behavior.steering;

import java.util.List;
import java.util.Random;

import javax.vecmath.Point2d;
import javax.vecmath.Vector2d;

import fr.utbm.gi.vi51.project.behavior.WanderBehaviour;

/**
 * Steering Wander Behaviour.
 * 
 * @author St&eacute;phane GALLAND &lt;stephane.galland@utbm.fr&gt;
 * @version $Name$ $Revision$ $Date$
 */
public class SteeringWanderBehaviour implements WanderBehaviour<SteeringBehaviourOutput> {


	/**
	 * @param circleDistance is the distance between the entity and the circle center.
	 * @param circleRadius is the radius of the circle.
	 * @param maxRotation is the maximal rotation of the entity.
	 * @param faceBehaviour is the face behaviour to use to face the target point on the circle.
	 */
	public SteeringWanderBehaviour(){
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public SteeringBehaviourOutput runWander(Point2d position, Vector2d orientation, double linearSpeed,
			double maxLinearAcc, double angularSpeed, double maxAngularAcc, List<Point2d> obstacle_tab) {
		SteeringBehaviourOutput output = new SteeringBehaviourOutput();
		Vector2d totalRepuls = new Vector2d();
		Vector2d direction = new Vector2d();
		for (Point2d obstacle : obstacle_tab) {
			Vector2d obstacleRepuls = new Vector2d(position.getX() - obstacle.getX(), position.getY()
					- obstacle.getY());
			double distance = obstacleRepuls.length();
			if (obstacleRepuls.length() < 30) {
				obstacleRepuls.scale(Math.exp(1 / distance) + 3);
				totalRepuls.setX(totalRepuls.getX() + obstacleRepuls.getX());
				totalRepuls.setY(totalRepuls.getY() + obstacleRepuls.getY());
			}
		}

		direction.setX(orientation.getX() + totalRepuls.getX());
		direction.setY(orientation.getY() + totalRepuls.getY());

		direction.scale(orientation.length());
		// Angular
		double angular = (new Random().nextDouble() - new Random().nextDouble()) * maxAngularAcc;
		output.setAngular(angular);
		// Linear
		Vector2d linear = new Vector2d(direction);
		linear.normalize();
		output.setLinear(linear);
		return output;
	}

}